package xuecheng.tool.mq.rabbitmq;

import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

import lombok.extern.slf4j.Slf4j;

/**
 * RabbitMQ配置，主要是配置队列，如果提前存在该队列，可以省略本配置类
 *
 * @author PengXueCheng
 * @version 1.0.0
 **/
@Slf4j
@SpringBootConfiguration
@EnableRabbit
public class CpxRabbitMqAutoConfig {

    /**
     * 使用 json 作为消息的序列化方式
     *
     * @return
     */
    @Bean
    public MessageConverter jackson2JsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 配置消息发送成功回调方法
     *
     * @return
     */
    @Bean
    public RabbitTemplate.ConfirmCallback confirmCallback() {
        return (correlationData, ack, cause) -> log.info("消息发送成功:correlationData({}),ack({}),cause({})",
            correlationData, ack, cause);
    }

    /**
     * 配置消息丢失回调方法
     *
     * @return
     */
    @Bean
    public RabbitTemplate.ReturnCallback returnCallback() {
        return (message, replyCode, replyText, exchange, routingKey) -> log.info(
            "消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}", exchange, routingKey, replyCode,
            replyText, message);
    }

    // @Bean
    // public RabbitTemplate rabbitTemplate(CachingConnectionFactory connectionFactory) {
    // connectionFactory.setPublisherConfirms(true);
    // connectionFactory.setPublisherReturns(true);
    // RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
    // rabbitTemplate.setMandatory(true);

    // RabbitTemplate.ConfirmCallback confirmCallback = (correlationData, ack, cause) -> log
    // .info("消息发送成功:correlationData({}),ack({}),cause({})", correlationData, ack, cause);
    // rabbitTemplate.setConfirmCallback(confirmCallback);
    //
    // RabbitTemplate.ReturnCallback returnCallback = (message, replyCode, replyText, exchange, routingKey) -> log
    // .info("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}", exchange, routingKey, replyCode,
    // replyText, message);
    // rabbitTemplate.setReturnCallback(returnCallback);
    // return rabbitTemplate;
    // }

}
